package com.zlp.controller;

import com.zlp.dto.UserLoginVO;
import com.zlp.entity.SysUser;
import com.zlp.service.SysUserService;
import com.zlp.utils.api.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 后台用户管理
 * @author ：ZouLiPing
 * @date ： 2019/10/8 16:45
 */
@RestController
@Api(tags = "后台用户管理")
@RequestMapping("user")
@Slf4j
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;


    @ApiOperation(value = "登录以后返回token")
    @PostMapping(value = "login")
    public CommonResult login(@RequestBody @Validated UserLoginVO userLoginVO) {
        log.info("第二步======================》登录验证");
        String token = sysUserService.login(userLoginVO.getUserCode(), userLoginVO.getPassword());
        if (StringUtils.isEmpty(token)) {
            return CommonResult.validateFailed("用户名或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>(2);
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }

    @ApiOperation(value = "用户注册")
    @PostMapping(value = "register")
    public CommonResult<SysUser> register(SysUser sysUserVO) {
        log.info("用户注册==》userCode:{},password:{}",sysUserVO.getUserCode(),sysUserVO.getPassword());
        SysUser sysUser = sysUserService.register(sysUserVO);
        if (sysUser == null) {
            CommonResult.failed();
        }
        return CommonResult.success(sysUser);
    }


    @ApiOperation(value = "用户注册")
    @PostMapping(value = "registerTest")
    public CommonResult<SysUser> registerTest(String password,String userCode) {
        log.info("用户注册==》userCode:{},password:{}",userCode,password);
        SysUser sysUser = new SysUser();
        sysUser.setUserCode(userCode);
        sysUser.setPassword(password);
        sysUser = sysUserService.register(sysUser);
        if (sysUser == null) {
            CommonResult.failed();
        }
        return CommonResult.success(sysUser);
    }

    @ApiOperation(value = "获取用户信息")
    @GetMapping(value = "getUserInfo")
    public CommonResult<SysUser> getUserInfo(String userCode) {
        SysUser sysUser = sysUserService.getUserInfo(userCode);
        if (sysUser == null) {
            CommonResult.failed();
        }
        return CommonResult.success(sysUser);
    }
}
